<template>
	<n-space vertical>
		<n-space>
			<n-input
				v-model:value="searchKeyword"
				placeholder="搜索模板名称"
				style="width: 300px; margin-right: 10px"
			></n-input>
			<n-button type="primary" @click="searchTemplates">刷新</n-button>
			<n-button type="primary" @click="addTemplate">新增模板</n-button>
		</n-space>
		<!-- 模板列表 -->
		<n-data-table
			:columns="columns"
			:data="templateData"
			:pagination="pagination"
			:row-key="(row) => row.id"
			:scroll-x="1500"
			class="template-table"
		>
			<template #cell:actions="{ row }">
				<n-button type="primary" text size="small" @click="editTemplate(row)"
					>编辑</n-button
				>
				<n-button type="error" text size="small" @click="deleteTemplate(row)"
					>删除</n-button
				>
			</template>
		</n-data-table>
	</n-space>

	<!-- 模板编辑对话框 - 确保使用n-modal的标准配置 -->
	<n-modal v-model:show="showModal">
		<n-card
			:title="modalTitle"
			style="width: 600px; height: 100%; position: fixed; right: 0px; top: 0px"
			:bordered="false"
			role="dialog"
			aria-modal="true"
		>
			<template #header-extra> </template>
			<n-space vertical>
				<n-form :model="formData" :rules="rules" ref="formRef">
					<n-form-item path="title" label="模板标题">
						<n-input
							v-model:value="formData.title"
							placeholder="请输入模板标题"
						/>
					</n-form-item>
					<n-form-item path="templateId" label="模板ID">
						<n-input
							v-model:value="formData.templateId"
							placeholder="请输入模板ID"
						/>
					</n-form-item>
					<n-form-item path="content" label="模板内容">
						<n-input
							v-model:value="formData.content"
							type="textarea"
							rows="4"
							placeholder="请输入模板内容"
						/>
					</n-form-item>
					<n-form-item path="example" label="示例数据">
						<n-input
							v-model:value="formData.example"
							type="textarea"
							rows="3"
							placeholder="请输入示例数据"
						/>
					</n-form-item>
					<n-form-item path="status" label="状态">
						<n-select
							v-model:value="formData.status"
							:options="statusOptions"
							placeholder="请选择状态"
						/>
					</n-form-item>
				</n-form>
			</n-space>
			<template #footer>
				<n-space>
					<n-button @click="showModal = false">取消</n-button>
					<n-button type="primary" @click="handleSubmit">确定</n-button>
				</n-space>
			</template>
		</n-card>
	</n-modal>
</template>

<script setup>
	import { ref, onMounted, reactive } from "vue";
	import templateMessageApi from "@server/api/templateMessageApi";
	// 替换 window.$dialog 为 useMessage
	import { useMessage } from "naive-ui";
	const message = useMessage();

	// 表格列配置
	const columns = [
		{ title: "模板标题", key: "title", width: 100, fixed: "left" },
		{ title: "模板ID", key: "templateId", width: 120, fixed: "left" },
		{
			title: "状态",
			key: "status",
			width: 100,
			render: (row) => (row.status === 1 ? "启用" : "禁用"),
		},
		{ title: "模板内容", key: "content", width: 300 },
		{ title: "示例数据", key: "example", width: 300 },
		{ title: "创建时间", key: "createTime", width: 120, fixed: "right" },
		{ title: "操作", key: "actions", width: 120, fixed: "right" },
	];

	// 模板数据
	const templateData = ref([
		// 模拟数据
		{
			id: "1",
			title: "订单通知",
			templateId: "OPENTM408731555",
			content: "您有一个新订单 #{{orderNo.DATA}}#，请及时处理。",
			example: '{"orderNo": {"value": "123456789"}}',
			status: 1,
			createTime: "2023-01-01 10:00:00",
			updateTime: "2023-01-01 10:00:00",
		},
		{
			id: "2",
			title: "活动通知",
			templateId: "OPENTM408731556",
			content:
				"亲爱的用户，#{{userName.DATA}}#，您关注的活动 #{{activityName.DATA}}# 即将开始。",
			example:
				'{"userName": {"value": "张三"}, "activityName": {"value": "春节活动"}}',
			status: 1,
			createTime: "2023-01-02 15:30:00",
			updateTime: "2023-01-02 15:30:00",
		},
	]);

	// 分页配置
	const pagination = ref({
		pageSize: 10,
		pageCount: 1,
		currentPage: 1,
		total: 0,
	});

	// 搜索关键词
	const searchKeyword = ref("");

	// 状态选项
	const statusOptions = [
		{ label: "启用", value: 1 },
		{ label: "禁用", value: 0 },
	];

	// 对话框状态
	const showModal = ref(false);
	const modalTitle = ref("新增模板");

	// 表单数据
	const formData = reactive({
		id: "",
		title: "",
		templateId: "",
		content: "",
		example: "",
		status: 1,
	});

	// 表单验证规则
	const rules = {
		title: [{ required: true, message: "请输入模板标题", trigger: "blur" }],
		templateId: [{ required: true, message: "请输入模板ID", trigger: "blur" }],
		content: [{ required: true, message: "请输入模板内容", trigger: "blur" }],
	};

	// 表单引用
	const formRef = ref();

	// 获取模板数据 - 修改为使用 useMessage
	const fetchTemplateData = async () => {
		try {
			const data = await templateMessageApi.getTemplateList({
				page: pagination.value.currentPage,
				pageSize: pagination.value.pageSize,
				keyword: searchKeyword.value,
			});
			templateData.value = data.data;
			pagination.value.total = data.total;
			pagination.value.pageCount = Math.ceil(
				data.total / pagination.value.pageSize
			);
		} catch (error) {
			console.error("获取模板数据失败:", error);
			message.error("获取模板数据失败，请稍后重试");
		}
	};

	// 删除模板 - 修改为使用 useMessage
	const deleteTemplate = async (row) => {
		if (confirm(`确定要删除模板 "${row.title}" 吗？`)) {
			try {
				await templateMessageApi.deleteTemplate(row.id);
				fetchTemplateData();
				message.success("模板删除成功");
			} catch (error) {
				console.error("删除模板失败:", error);
				message.error("删除模板失败，请稍后重试");
			}
		}
	};

	// 提交表单 - 修改为使用 useMessage
	const handleSubmit = async () => {
		if (!formRef.value) return;
		try {
			await formRef.value.validate();
			if (formData.id) {
				await templateMessageApi.updateTemplate(formData);
				message.success("模板更新成功");
			} else {
				await templateMessageApi.addTemplate(formData);
				message.success("模板添加成功");
			}
			showModal.value = false;
			fetchTemplateData();
		} catch (error) {
			console.error("表单验证或提交失败:", error);
			message.error("操作失败，请稍后重试");
		}
	};

	// 搜索模板
	const searchTemplates = () => {
		pagination.value.currentPage = 1;
		fetchTemplateData();
	};

	// 新增模板
	const addTemplate = () => {
		modalTitle.value = "新增模板";
		Object.keys(formData).forEach((key) => {
			formData[key] = "";
		});
		formData.status = 1; // 默认启用
		showModal.value = true;
	};

	// 编辑模板
	const editTemplate = (row) => {
		modalTitle.value = "编辑模板";
		Object.assign(formData, row);
		showModal.value = true;
	};

	// 在组件挂载时加载数据
	onMounted(() => {
		fetchTemplateData();
	});
</script>